﻿using LD.Host;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;

namespace LD.Common
{
    public class HttpRequestHelper
    {

        /// <summary>
        /// 向指定URL发送POST请求(同步)
        /// </summary>       
        /// <param name="postData">发送的实体类</param>
        /// <returns>返回字符串</returns>
        public static T Post<T>(string postUrl, object postData)
        {

            StringBuilder sb = new StringBuilder();
            try
            {
                Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
                JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
                {
                    setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                    setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    return setting;
                });
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(postUrl);
                webRequest.Method = "POST";
                webRequest.Accept = "application/json, text/javascript, */*;";
                webRequest.ContentType = "text/json";

                webRequest.Headers.Add("xxx", "xxx");

                string jsonPostDataStr = JsonConvert.SerializeObject(postData, setting);
                byte[] byteArray = Encoding.UTF8.GetBytes(jsonPostDataStr);
                if (jsonPostDataStr.Length > 0)
                {
                    webRequest.ContentLength = byteArray.Length;
                }
                //LoggingFactory.GetLogger().Log(jsonPostDataStr);//下边记过了。

                sb.AppendLine("Send--->>>");
                sb.AppendLine("post url:" + postUrl);
                sb.AppendLine(jsonPostDataStr);
                //请求
                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);
                newStream.Close();
                //返回
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                var responSteam = response.GetResponseStream();
                StreamReader strRespon = new StreamReader(responSteam, Encoding.UTF8);
                string resultStr = strRespon.ReadToEnd();
                sb.AppendLine("Recive<<<---");
                sb.AppendLine(resultStr);
                T result = JsonConvert.DeserializeObject<T>(resultStr);//反序列化
                return result;
            }

            catch (Exception ex)
            {
                sb.AppendLine("Error<<<---");
                sb.AppendLine(ex.Message);
                return default(T);
            }
        }

        /// <summary>
        /// 向指定URL发送POST请求(同步)
        /// </summary>       
        /// <param name="postData">发送的实体类</param>
        /// <returns>返回字符串</returns>
        public static T Post<T>(string postUrl, string postData)
        {

            StringBuilder sb = new StringBuilder();
            try
            {
                //Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
                //JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
                //{
                //    setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                //    setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                //    return setting;
                //});
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(postUrl);
                webRequest.Method = "POST";
                webRequest.Accept = "application/json, text/javascript, */*;";
                webRequest.ContentType = "text/json";

                webRequest.Headers.Add("xxx", "xxx");

                // string jsonPostDataStr = JsonConvert.SerializeObject(postData, setting);
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                if (postData.Length > 0)
                    webRequest.ContentLength = byteArray.Length;

                //LoggingFactory.GetLogger().Log(jsonPostDataStr);//下边记过了。

                sb.AppendLine("Send--->>>");
                sb.AppendLine("post url:" + postUrl);
                sb.AppendLine(postData);
                //请求
                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                var responSteam = response.GetResponseStream();
                StreamReader strRespon = new StreamReader(responSteam, Encoding.UTF8);
                string resultStr = strRespon.ReadToEnd();
                sb.AppendLine("Recive<<<---");
                sb.AppendLine(resultStr);
                T result = JsonConvert.DeserializeObject<T>(resultStr);//反序列化
                return result;
            }

            catch (Exception ex)
            {
                sb.AppendLine("Error<<<---");
                sb.AppendLine(ex.Message);
                return default(T);
            }
        }
        public static string Post(string postUrl, string postData)
        {

            try
            {
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(postUrl);
                webRequest.Method = "POST";
                webRequest.Accept = "application/json, text/javascript, */*;";
                webRequest.ContentType = "text/json";

                //webRequest.Headers.Add("xxx", "xxx");
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                if (postData.Length > 0)
                    webRequest.ContentLength = byteArray.Length;

                //请求
                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                var responSteam = response.GetResponseStream();
                StreamReader strRespon = new StreamReader(responSteam, Encoding.UTF8);
                string resultStr = strRespon.ReadToEnd();
                return resultStr;
            }

            catch (Exception)
            {
                return string.Empty;
            }
        }
        /// <summary>
        /// 向指定URL发送POST请求(同步)
        /// </summary>       
        /// <param name="postData">发送的实体类</param>
        /// <returns>返回字符串</returns>
        public static T Get<T>(string getUrl, object postData)
        {
            Log4.Info("MES请求:" + getUrl);
            try
            {
                Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
                JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
                {
                    setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                    setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    return setting;
                });
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(getUrl);
                webRequest.Method = "GET";
                webRequest.Accept = "application/json, text/javascript, */*;";
                webRequest.ContentType = "text/json";

                webRequest.Headers.Add("xxx", "xxx");

                //请求
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                var responSteam = response.GetResponseStream();
                StreamReader strRespon = new StreamReader(responSteam, Encoding.UTF8);
                string resultStr = strRespon.ReadToEnd();
                Log4.Info("MES返回:" + resultStr);

                T result = JsonConvert.DeserializeObject<T>(resultStr);//反序列化
                return result;
            }

            catch (Exception ex)
            {
                Log4.Error("MES请求异常:" + ex.Message);
                return default(T);
            }
        }
        public static string Get(string getUrl)
        {
            string resultStr = string.Empty;
            try
            {
                Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
                JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
                {
                    setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                    setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    return setting;
                });
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(getUrl);
                webRequest.Method = "GET";
                webRequest.Accept = "application/json, text/javascript, */*;";
                webRequest.ContentType = "text/json";
                //webRequest.Headers.Add("xxx", "xxx");
                //请求
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                var responSteam = response.GetResponseStream();
                StreamReader strRespon = new StreamReader(responSteam, Encoding.UTF8);
                resultStr = strRespon.ReadToEnd();
            }
            catch (Exception ex)
            {
                Log4.Error("MES请求异常:" + ex.Message);
            }
            return resultStr;
        }
        /// <summary>
        /// 向指定URL发送POST请求(同步)
        /// </summary>       
        /// <param name="postData">发送的实体类</param>
        /// <returns>返回字符串</returns>
        public static T PostForm<T>(string postUrl, string postData)
        {
            //Ilogger _logger = LoggingFactory.GetLogger();
            StringBuilder sb = new StringBuilder();
            try
            {
                Newtonsoft.Json.JsonSerializerSettings setting = new Newtonsoft.Json.JsonSerializerSettings();
                JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
                {
                    setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
                    setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    return setting;
                });
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(postUrl);
                webRequest.Method = "POST";
                webRequest.Accept = "application/json, text/javascript, */*;";
                webRequest.ContentType = "application/x-www-form-urlencoded";

                //webRequest.Headers.Add("gmsoperater", "gmsscm");
                //webRequest.Headers.Add("gmsappkey", "16dc87055ab6429a803df2217a14b36d");
                //webRequest.Headers.Add("gsmappsecret", "0d91f4acb7eb441aa72c825e414f9122");

                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                if (postData.Length > 0)
                    webRequest.ContentLength = byteArray.Length;

                sb.AppendLine("Send--->>>");
                sb.AppendLine("post url:" + postUrl);
                sb.AppendLine(postData);
                //请求
                Stream newStream = webRequest.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
                var responSteam = response.GetResponseStream();

                StreamReader strResponUTF8 = new StreamReader(responSteam, System.Text.Encoding.UTF8);
                string result = strResponUTF8.ReadToEnd();

                //result = HttpUtility.UrlDecode(result, Encoding.UTF8);

                T model = JsonConvert.DeserializeObject<T>(result);//反序列化

                sb.AppendLine("Recive<<<---");
                sb.AppendLine(result);

                return model;
            }
            catch (Exception ex)
            {
                sb.AppendLine("Error<<<---");
                sb.AppendLine(ex.Message);
                Console.WriteLine(ex.Message);
                return default(T);
            }
        }
    }
}
